/*
 * @Project_description: http封装
 */
'use strict'

import qs from 'qs'
// 引入配置文件
import config from '../config.js'
//设置基础路径
const baseUrl = config.baseUrl

const http = {}

const message = (msg = '请求错误') => {
  uni.showToast({
    title: msg,
    icon: 'none',
  })
}

/**
 * @description 接口封装
 * @return {Promise} 返回值描述
 * @param options {Object} 参数说明
 */
const request = (options) => {
  if (options.params) {
    options.url = options.url + '?' + qs.stringify(options.params)
  }
  const url = baseUrl ? baseUrl + options.url : options.url
  const header = options.header||{}
  const token = uni.getStorageSync('_kw_user_token')
  if (token) header['Authorization'] = 'Bearer ' + token
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      data: options.data,
      header,
      method: options.method,
      dataType: options.dataType || 'json',
      timeout: options.timeout || 60000,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          message(res.data)
          console.error(res)
          reject(res)
        }
      },
      fail: (err) => {
        message(err.data)
        console.error(err)
        reject(err)
      },
    })
  })
}

/**
 * @description get请求封装
 * @return {Promise} 返回值描述
 * @param url {String}
 * @param [params] {Object} 参数
 * @param [header] {Object} 请求头
 */
http.get = (url, params, header) => {
  return request({
    url,
    params,
    header,
    method: 'get',
  })
}
/**
 * @description post请求封装
 * @return {Promise} 返回值描述
 * @param url {String}
 * @param [data] {Object} 参数
 * @param [header] {Object} 请求头
 */
http.post = (url, data, header) => {
  return request({
    url,
    data,
    header,
    method: 'post',
  })
}

/**
 * @description delete请求封装
 * @return {Promise} 返回值描述
 * @param url {String}
 * @param [data] {Object} 参数
 * @param [header] {Object} 请求头
 */
http.del = (url, data, header) => {
  return request({
    url,
    data,
    header,
    method: 'delete',
  })
}
/**
 * @description put请求封装
 * @return {Promise} 返回值描述
 * @param url {String}
 * @param [data] {Object} 参数
 * @param [header] {Object} 请求头
 */
http.put = (url, data, header) => {
  return request({
    url,
    data,
    header,
    method: 'put',
  })
}

/**
 * @description 上传文件封装
 * @return {Promise} 返回值描述
 * @param url {String} 接口地址
 * @param filePath {String} 文件路径
 * @param [name]  {String}文件名
 * @param [formData]  {Object} 表单数据
 * @param [header] {Object} 请求头
 */
http.upload = (url, filePath, name = 'file', formData = {}, header = {}) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url,
      filePath,
      name,
      formData,
      header,
      timeout: 600000,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(JSON.parse(res.data))
        } else {
          reject(res)
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/**
 * @description 上传文件封装
 * @return {Promise} 返回值描述
 * @param url {String} 接口地址
 * @param path {String} 文件路径
 * @param [name]  {String}文件名
 * @param [params]  {Object} 表单数据
 * @param [header] {Object} 请求头
 */
http.uploadFile = (
  url,
  path,
  params = {},
  header = {},
  name = 'excel_file_stream'
) => {
  console.log(url,path,params,header,name)
  return new Promise((resolve, reject) => {
    // 设置基础路径
    let httpUrl = baseUrl ? baseUrl + url : url
    if (Object.keys(params).length !== 0) {
      httpUrl = httpUrl + '?' + qs.stringify(params)
    }
    const baseHeader = header
    const token = uni.getStorageSync('_kw_user_token')
    if (token) baseHeader['Authorization'] = 'Bearer ' + token
    uni.uploadFile({
      url: httpUrl,
      file:path,
      name,
      header:baseHeader,
      timeout: 600000,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(JSON.parse(res.data))
        } else {
          reject(res)
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/**
 * @description 下载文件封装
 * @return {Promise} 返回值描述
 * @param urlPath {String} 接口地址
 * @param [data]  {Object} 表单数据
 * @param [header] {Object} 请求头
 */
http.downloadFile = (urlPath, data = {}, header = {}) => {
  const baseHeader = header.header || {}
  const token = uni.getStorageSync('_kw_user_token')
  if (token) baseHeader['Authorization'] = 'Bearer ' + token
  let url = baseUrl ? baseUrl + urlPath : urlPath

  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      data,
      header: baseHeader,
      method: 'post',
      responseType: 'arraybuffer', // 修改为responseType
      timeout: 60000,
      success: (res) => {
        if (res.statusCode === 200) {
          // 获取文件名
          const disposition = res.header['content-disposition']
          let fileName = '导出数据.xlsx'
          if (disposition) {
            const matches = disposition.match(
              /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
            )
            if (matches && matches[1]) {
              fileName = decodeURIComponent(matches[1].replace(/['"]/g, ''))
            }
          }

          // 获取正确的MIME类型
          const contentType =
            res.header['content-type'] ||
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

          // 创建blob对象时指定正确的MIME类型
          const blob = new Blob([res.data], { type: contentType })

          // 创建下载链接
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob)

          downloadElement.href = href
          downloadElement.download = fileName
          document.body.appendChild(downloadElement)
          downloadElement.click()
          message('下载成功')

          // 清理
          setTimeout(() => {
            document.body.removeChild(downloadElement)
            window.URL.revokeObjectURL(href)
          }, 100)

          return resolve(true)
        } else {
          message(res.msg || '下载失败')
          console.error('请求错误statusCode!=200', res)
          reject(res)
        }
      },
      fail: (err) => {
        message('下载失败')
        console.error('请求错误', err)
        reject(err)
      },
    })
  })
}

export default http
